<?php

function getRandChar($length){
    
   $str = null;
   
   $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
   
   $max = strlen($strPol)-1;

   for($i=0;$i<$length;$i++){
       
    $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    
   }
   
   return $str;
   

  }
  
  /**
   * 获取地区数据列表
   * @return $yn_json bool 是否返回json数据
   * @return \Think\mixed
   */
  function get_region_list($yn_json = FALSE){
      
      if($yn_json)
      
        return  json_encode(M('region')->cache(true)->select());
      
      else

        return M('region')->cache(true)->select();
      
  }
  
  /**
   * 获取当前页面完整URL地址
   */
  function get_url() {
      $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
      $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
      $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
      $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
      $host = $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
      if(strpos($relate_url, $host) !== false) $relate_url = str_replace($host,'', $relate_url);
      return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
  }
  
  /**
   * 上传方法
   * @param string $fileType 内容类型 image：图片；file：文件
   * @param string $contType pub 项目图标; pri 受保护的文件
   * @param array $config 配置信息
   */
  function uploadFile($file='',$fileType='pub',$contType='image',$config=array()){
      //上传文件的类型
      $typeArr = array('image'=>array('jpg', 'gif', 'png', 'jpeg'),'file'=>array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'txt', 'zip', 'rar', 'gz', 'bz2','apk'));
      
      //文件保存跟目录
      $dirArr = array('pub'=>'show','pri'=>'private');

      if(!$typeArr[$contType] || !$dirArr[$fileType]) return false;
      
      $hash = md5(time());
      
      $dst = $hash[0].'/'.$hash[1];
      //上传时默认属性
      if(empty($config)) $config=array('maxSize'=>3145728);
      //文件名唯一
      if (!isset($config['saveName']))
      {
      	$config['saveName'] = array('uniqid','');
      }	
      //准许文件类型
      $config['exts'] = $typeArr[$contType];
      //保存文件目录
      $config['subName'] = $dirArr[$fileType].'/'.$dst;
      //默认驱动为vfs
      $config['driver'] = 'vfs';

      $upload = new \Think\Upload($config);

      $file = $upload->upload($file);

      if(!$file){
          
          echo $upload->getError();exit;
          
      }else{
          
          return $file;
          
      }
  
  }
 

/**
 *  拼上传文件url
 */
function getFileUrl($url, $alias_path = '')
{
    $url = trim($url);
    if(empty($url)){
        return '';
    }

	if(strpos($url,'http://') !== false){
		return $url;
	}

    $base = rtrim($_SERVER['SRV_NDATA_URL'], '/').'/';
    $url = ltrim($url, '/');
    if (!empty($alias_path))
    {
    	$alias_path = ltrim($alias_path, '/') . '/';
    }	

    return $base . $alias_path . $url;
}

//获取绝对路径
function getFilePath($url)
{
    $url = ltrim($url, '/');
    return rtrim($_SERVER['SRV_NDATA_DIR'], '/').'/'.$url;
}

//获取自定义路径  替换掉 url已经 目录 为对应变量
function getCustomPath($path, $replace = '')
{
	return str_replace($_SERVER['SRV_NDATA_URL'] . $_SERVER['SRV_DATA_PATH'], $replace, $path);
}

//获取真实路径 
function getRealPathFromCustom($path, $source = '')
{
	return str_replace($source, $_SERVER['SRV_NDATA_URL'] . $_SERVER['SRV_DATA_PATH'], $path);
}

/**
 * 加密解密函数
 * $operation DECODE ENCODE
 *
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{

    $ckey_length = 4;

    if ($operation == 'DECODE') {
        //解密时将 -号转回+号，_号转回/
        $string = str_replace(array('-', '_'), array('+', '/'), $string);
    }

    //$key = md5($key ? $key : UC_KEY);
    $key  = md5($key);
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey   = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string        = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box    = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j       = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp     = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a       = ($a + 1) % 256;
        $j       = ($j + $box[$a]) % 256;
        $tmp     = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        $string = $keyc . str_replace('=', '', base64_encode($result));
        //加密时将 +号转为-号，/号转成_号, 以便于在url中传输
        return str_replace(array('+', '/'), array('-', '_'), $string);
    }
}

//生成静态文件url
function staticUrl($path)
{
    return '/Public/account/'.$path;
}

/**
 * 过滤富文本编辑器提交的html代码
 * @param string $htmlStr html代码
 * @param array $config 配置文件
 *  $conf = array(
            array('HTML.AllowedElements', array('div' => true,'table' => true,'tr' => true,'td' => true,br' => true,),false), //允许属性 div table tr td br元素
            array('HTML.AllowedAttributes', array('class' => TRUE), false),     //允许属性 class
            array('Attr.ForbiddenClasses', array('resume_p' => TRUE), false),   //禁止classes 名为resume_p
            array('AutoFormat.RemoveEmpty', true, false),              //去空格
            array('AutoFormat.RemoveEmpty.RemoveNbsp', true, false),       //去nbsp
            array('URI.Disable', true, false),
        );
 * @return string 过滤后的html代码
 */
function HTMLPurifier($htmlStr,$config = array()){
    
    require_once APP_PATH.'/Lib/HTMLPurifier/HTMLPurifier.auto.php';
    
    if(empty($config)) $config = HTMLPurifier_Config::createDefault();
   
    $p = new Resume_HtmlPurifier($config);
    
    return $p->filter($htmlStr);
    
}
/**
 * 添加回滚日志
 *
 * @param string $act_name 再哪个方法调用的
 * @param string $params 需要调试的参数，可随便的填写，以日后方便调试为主
 * @param string $remake 备注，可填写简单的记录说明
 * @param array $ext_params 扩展数组，暂时没有用到，当需要填写多个参数的时候可以试用扩展数组
 * @return bool
 */
function addLogs($act_name = '', $params = '', $remake = '', $ext_params = array())
{
    //调试错误
    // var_dump($remake);exit;
    $model = new \Common\Model\RollbackLogModel();
    $model->addLog($act_name,$params,$remake,$ext_params);
    unset($model);
    return true;
}

/**
 * 用指定的字符（$replace）替换$str
 * 例如：replaceStar('22011984157541890X', 3, 3, '*')
 * 返回：220************90X
 *
 * @param string $str 准备需要替换字符的字符串
 * @param int $prefix_len 前置字符长度
 * @param int $suffix_len 后置字符长度
 * @param string $replace 替换的字符
 * @param string $charact 字符集
 * @return string
 */
function replaceStar($str = '', $prefix_len = 0, $suffix_len = 0, $replace = '*', $charact = 'utf-8')
{
    $length = mb_strlen($str, $charact);
    //避免处理后的字符比原字符还要长，进行一次判断 add by shang
    if(($prefix_len+$suffix_len)>$length)return $str;
    $str = mb_substr($str, 0, $prefix_len, $charact).str_repeat($replace, ($length-$prefix_len-$suffix_len)).mb_substr($str, $length-$suffix_len, $suffix_len, $charact);
    return $str;
    // return mb_substr($str, 0, $start, $charact).str_repeat($replace, $len).mb_substr($str, $start+$len, mb_strlen($str, $charact), $charact);
}

/*
//对记录集进行星号替换
//参数:
$role 批量过滤规则:  [字段] =>array(前置字符长度,后置字符长度,'pass'=>array('不需要过滤的Controller名称1','不需要过滤的Controller名称2')),
*/
function replaceStar2(&$data,$role=array())
{
    !is_array($role) && $role = array();
    if(empty($role)){
        return false;
    }
    if(empty($data) || !is_array($data)){
        return false;
    }

    $keys = array_keys($role);
    foreach($data as &$r){
        foreach($r as $key=>&$val){
            if(in_array($key,$keys) && !is_array($val)){
                $pass = $role[$key]['pass'];
                !is_array($pass) &&  $pass = array($pass);
                $pass = array_map('trim',$pass);
                //不过滤白名单中的对应字段
                if(!in_array(CONTROLLER_NAME,$pass)) {
                    $val = replaceStar(trim($val), $role[$key][0], $role[$key][1]);
                }
            }
        }
    }

    return true;
}


/**
 * 替换姓名
 *
 * @param string $str
 * @param string $replace
 * @param string $charact
 * @return string
 */
function replaceRealName($str = '', $replace = '*', $charact = 'utf-8') {
    $length = mb_strlen($str, $charact);
    if ( $length > 2 ) {
        $str = mb_substr($str, 0, 1, $charact).str_repeat($replace, ($length-2)).mb_substr($str, -1, 1, $charact);
    }
    else{
        $str = mb_substr($str, 0, 1, $charact).$replace;
    }
    return $str;
}

/**
 * 格式化 项目金额
 * @param  [float] $money 要处理的钱数
 * @param  float  $unit  单位.默认为万
 * @return $money
 */
function formatMoney($money, $unit=10000.00)
{
    $money = bcdiv($money, $unit, 2);
    if($pos=strpos($money, '.00'))
    {
        $money = substr($money, 0, $pos);
    }
    return $money;
    
}

function stripNull(&$v, $k)
{
  if(is_null($v))
  {
    $v = '';
  }
  // elseif(is_numeric($v))
  // {
  //   $v = (string)$v;
  // }
}

/**
 * 格式化发给连连的uid
 * @param $uid
 * @return string
 */
function formatLLUid($uid)
{
    $prefix = isset($_SERVER['ENV_NAME']) ? $_SERVER['ENV_NAME'] : 'localhost';

    return $prefix.'_'.$uid;
}

/**
 * 获取两个时间戳之间的天数
 */
function getDays($endTime,$startTime=NULL){
    
    //开始日期
    $startTime = empty($startTime) ? strtotime('today') : $startTime;
    $startDate = is_numeric($startTime) ? $startTime : strtotime($startTime);
    //结束日期
    $endDate = is_numeric($endTime) ? $endTime : strtotime($endTime);
    $times = abs($endDate - $startDate);
    return intval($times/(24*3600)+1);
}

function pz_close()
{
return false;
}
/*
 * 根据身份证获取省份
 */
function getCityByMobile($mobile)
{
    $url = 'http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile=' . $mobile;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $return_str = curl_exec($ch);
    //var_dump($return_str);
    if(curl_exec($ch) === false)
    {
        die('Curl error: ' . curl_error($ch));
    }

    curl_close($ch);
    if (empty($return_str))
    {
        return false;
    }
    $xml = simplexml_load_string($return_str);

    $data = array();
    $data['city'] = trim((string) $xml->city);
    $data['province'] = trim((string) $xml->province);

    return $data;
}

if(!function_exists("array_column"))
{
  function array_column(array $arr, $field)
  {
    $res = array();
    foreach ($arr as $key => $value) {
      if(array_key_exists($field, $value))
      $res[$key] = $value[$field];
    }
    return $res;
  }
}


/*
 * 根据身份证获取出生年月性别
 */
function getInfoByIdCard($idNo)
{
	$data = array();
	if(strlen($idNo) == 18)
	{
	   	//获取年份
	   	$data['year'] = substr($idNo,6,4);
	   	
	   	//获取月
	   	$data['month'] = substr($idNo,10,2);
	   	
	   	//获取日
	   	$data['day'] = substr($idNo,12,2);
	   	
	   	//获取身份证性别
	   	$sex = substr($idNo,16,1);
	}
	elseif(strlen($idNo) == 15)
	{
	   	$date=substr($idNo,6,2);
	   	//获取年
	   	$data['year'] = "19".$date;
	   	
	   	//获取月
	   	$data['month'] = substr($idNo,8,2);
	   	
	   	//获取日
	   	$data['day'] = substr($idNo,10,2);
	   	
	   	//获取身份证性别
	   	$sex = substr($idNo,14,1);
	}
	
	if($sex%2==0)
	{
	   $data['sex'] = 2;
	   $data['sex_cn'] = '女';
	}
	else 
	{
	   $data['sex'] = 1;
	   $data['sex_cn'] = '男';
	}
		
	return $data;
}

/**
 * 后台日志记录函数
 * @param array $user 用户信息
 * @param string $content 记录内容
 * @param string $actionCode 动作标志包括,array('index.login','index.logout','user.edit','user.add')等 默认为控制器名。方法名
 */
function action_log($user,$content,$action_code =  NULL){
       $model = D('AdminLog');
       if(!$action_code) $action_code = CONTROLLER_NAME.".".ACTION_NAME;
       $data['uid'] = $user['uid'];
       $data['user_name'] = $user['user_name'];
       $data['create_ip'] = $user['ip'];
       $data['action_code'] = $action_code;
       $data['content'] = $content;
       $data['create_time'] = NOW_TIME;
       return $model->data($data)->add();
}

function yun_to_fen($yun){
    
    return bcmul($yun,100);
}

function menu_init($module='')
{
    if(empty($module)) $module = 'Admin';
    $ret = array();
    $config_file = MODULE_PATH.'Conf/config_menu.php';
    if(!is_file($config_file))
    {
        return array();
    }
    $config_menu = require($config_file);
    $ret = $config_menu;
    foreach ($config_menu as $mk => $menu)
    {
        foreach ($menu['list'] as $lk => $item)
        {
            $check_url = $item['module'] ? $item['url'] : $module . '/'.$item['url'];
            /*if(!$item['url'] or !authCheck($check_url, session('uid')))
            {
                unset($ret[$mk]['list'][$lk]);
            }*/
        }
    }
    return $ret;
}

/**
 * 权限验证
 * @param rule string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param uid  int           认证用户的id
 * @param string mode        执行check的模式
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function authCheck($rule,$uid,$type=1, $mode='url', $relation='or'){
    //超级管理员跳过验证
    $auth=new \Think\Auth();
    //获取当前uid所在的角色组id
    $groups=$auth->getGroups($uid);
    session('gid',$groups[0]['group_id']);//角色组id
    session('gname',$groups[0]['title']);//角色组名称

    //设置的是一个用户对应一个角色组,所以直接取值.如果是对应多个角色组的话,需另外处理
    if(in_array($groups[0]['group_id'], C('ADMINISTRATOR'))){
        return true;
    }else if(in_array($rule, C('NO_AUTH_RULES'))){
        return true;
    }else{
        return $auth->check($rule,$uid,$type,$mode,$relation)?true:false;
    }
}

function getWorkSpaceList(){
    
    $file = CONF_PATH.'config_work_space.php';
    if(!is_file($file))
    {
        return array();
    }
    
    $list = require($file);
    
    $ret = $list;
    foreach ($list as $lk => $item)
    {
        if(!$item['authKey'] or !authCheck($item['authKey'],session('uid')))
        {
            unset($ret[$lk]);
        }
    }
    return $ret;
    
}

function array2csv($data)
{
  $ret = '';
  foreach ($data as $item)
  {
    $ret .= implode(',', $item)."\n";
  }
  return $ret;
}

function array2table($data, $head_data = array(), $table_header = '', $only_body = false)
{
  $header = $table_header ? $table_header : '<table>';

  $head = '<thead><tr>';
  foreach ($head_data as $key_c => $col_item)
  {
    $head .= "<th field=\"f-{$key_c}\">{$col_item}</th>";
  }
  $head .= '</tr></thead>';

  $body = '<tbody>';
  foreach ($data as $item)
  {
    $body .= '<tr><td>';
    $body .= implode('</td><td>', $item);
    $body .= '</td></tr>';
    // break;
  }
  $body .= '</tbody>';
  // var_dump($body);exit;
  $footer = '</table>';
  return $only_body ? ($head . $body) : ($header . $head . $body . $footer);  
}




/*
//对一组数据进行批量处理 与 DF类似，仅格式不同(相反)，但更适合批量规划
//格式化数组, 类型: 'int','text'
//$formatList = array(
	'类型名称'=>array(key1,key3,...), //将指定的一批key按规定的类型进行格式化 (或格式: 'key1,key3,....'
	'int'=>'key2,key4', //将'key2'和'key4'做为'int'处理
	'text'=>'key3,key4', //批量将所有字段都做为“text”处理(除显示指定的'key1'与'key2'之外)
) */
function DV($formatList=array(),$data=array())
{
    if(empty($data) || !is_array($data)){
        $data = I('request.');
    }

    if(empty($formatList) || !is_array($formatList)){
        return $data;
    }

    //格式化数据
    $redata = array();
    foreach($formatList as $key=>$val){
        $key = trim(strtolower($key));
        if(!is_array($val)){
            $val = explode(',',$val);
            $val = array_map('trim',$val);
        }

        foreach($val as $v){
            if(empty($v)){
                continue;
            }

            switch($key){
                case 'int':
                    $redata[$v] = intval($data[$v]);
                    break;
                default : //默认 text
                    $redata[$v] = trim($data[$v]);
            }
        }
    }

    return $redata;
}

/**
 * 编码整形数据
 */
function encodeint($val, $ver = 1)
{
    $hex = '0123456789abcdef';
    $codeBookV1 = '7lx92fjbrguakehz';

    switch ($ver) {
        case '1':
            $code = $codeBookV1;
            break;
        default:
            $ver = 1;
            $code = $codeBookV1;
            break;
    }


    $val = intval($val);
    return $ver.strtr(dechex($val), $hex, $code);
}

/**
 * 解码出整形数据,区分大小写，返回为0视为解码失败
 */
function decodeint($val)
{
    $ver = $val[0];
    $val = substr($val,1);
    $hex = '0123456789abcdef';
    $codeBookV1 = '7lx92fjbrguakehz';

    switch ($ver) {
        case '1':
            $code = $codeBookV1;
            break;
        default:
            $code = $codeBookV1;
            break;
    }
    return hexdec(strtr($val, $code, $hex));
}

//生成一个不重复的订单编号, 如: 20160415162335294316
function OrderId()
{
    $time = gettimeofday();
    return date('YmdHis').substr('00000'.$time['usec'],-6,6); //时间戳+当前毫微秒数
}

//是否在指定的闭区间之内
function between($val,$left,$right)
{
    return $left<=$val && $val<=$right;
}

//是否允许导出操作
function checkExportAuth()
{
	if (EXPORT_FLAG == false)
	{
		die('stop action');
	}
}
//根据生日获取星座
function getConstellation($month, $day)  
{ 
	$day   = intval($day);  
	$month = intval($month);  
	if ($month < 1 || $month > 12 || $day < 1 || $day > 31) return '';  
	$signs = array(  
			array('20'=>'水瓶座'),  
			array('19'=>'双鱼座'),  
			array('21'=>'白羊座'),  
			array('20'=>'金牛座'),  
			array('21'=>'双子座'),  
			array('22'=>'巨蟹座'),  
			array('23'=>'狮子座'),  
			array('23'=>'处女座'),  
			array('23'=>'天秤座'),  
			array('24'=>'天蝎座'),  
			array('22'=>'射手座'),  
			array('22'=>'摩羯座')  
	);  
	list($start, $name) = each($signs[$month-1]);  
	if ($day < $start)  
		list($start, $name) = each($signs[($month-2 < 0) ? 11 : $month-2]);  
	return $name;  
}

//当前环境是否是生产环境
function envProduct()
{
    return trim(strtolower($_SERVER['ENV_NAME'])) === 'product';
}

function setUserInfo( $user_info,  $cookie_sep = '_', $life_time = 86400)
{
    $cstr = $user_info['username'] . $cookie_sep . $user_info['uid'] . $cookie_sep . $user_info['lastlogintime'] . $cookie_sep . $user_info['realname'];
    //设置登录cookie
    $cookie = authcode($cstr, 'ENCODE', trim(C('DATA_AUTH_KEY')), $life_time);
    return setcookie('LCSUC', $cookie, time() + (int)$life_time, '/');
}

function getUserInfo( $cookie_sep = '_' )
{
    $cookie = authcode($_COOKIE['LCSUC'], 'DECODE', trim(C('DATA_AUTH_KEY')));
    return $cookie ? explode($cookie_sep, $cookie) : false;
}

function clearUserInfo( $cookie_sep = '_' )
{
    return setcookie('LCSUC', '', 0, '/');
}